package com.hillky.springboot.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hillky.springboot.controller.request.BaseRequest;
import com.hillky.springboot.entity.Book;
import com.hillky.springboot.entity.Category;
import com.hillky.springboot.mapper.BookMapper;
import com.hillky.springboot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    @Override
    public List<Book> list(){
        return bookMapper.list();
    }

    @Override
    public PageInfo<Book> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        List<Book> categories = bookMapper.listByCondition(baseRequest);
        return new PageInfo<>(categories);
    }

    @Override
    public void save(Book book) {
        book.setCategory(category(book.getCategoryList()));
        bookMapper.save(book);
    }

    @Override
    public Book getById(Integer id) {
        Book book=bookMapper.getById(id);
        return book;
    }

    @Override
    public void update(Book book) {
        book.setCategory(category(book.getCategoryList()));
        book.setUpdateTime(new Date());
        bookMapper.update(book);
        return;
    }

    @Override
    public void deleteById(Integer id) {
        bookMapper.deleteById(id);
        return;
    }

    private String category(List<String> str){
        StringBuilder sb = new StringBuilder();
        for (String s : str) {
            sb.append(s+">");
        }
        return sb.toString().substring(0,sb.lastIndexOf(">"));
    }
}
